//
//  BGComposeTextView.swift
//  WeiboSwift
//
//  Created by 战场原黑仪 on 16/7/29.
//  Copyright © 2016年 战场原黑仪. All rights reserved.
//

import UIKit

class BGComposeTextView: UITextView {
    
    //添加占位文字
    var placeholder: String? {
        didSet {
            placeholderLabel.text = placeholder
        }
    }
    
    //重写字体
    override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        setupLayout()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //通知方法
    @objc private func valueChange() {
        //根据textView有无文字决定placeholder是否显示
        placeholderLabel.hidden = self.hasText()
    }

    //MARK: - 设置视图
    private func setupUI() {
        backgroundColor = self.superview?.backgroundColor
        addSubview(placeholderLabel)
        //添加监听者
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(valueChange), name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    private func setupLayout() {
        // 添加约束
        placeholderLabel.snp_makeConstraints { (make) in
            make.leading.equalTo(self).offset(5)
            make.top.equalTo(self).offset(8)
            make.width.equalTo(self).offset(-10)
        }
    }
    
    //MARK: - 懒加载
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textColor = GrayColor
        return label
    }()
    
}
